package edu.hit.pact.pgse.master.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import edu.hit.pact.pgse.bean.Task;
import edu.hit.pact.pgse.communication.message.TaskPushMessage;
import edu.hit.pact.pgse.master.MasterManager;
import edu.hit.pact.pgse.master.util.CrawlerDeadHandler;

public class MasterClientHandler implements IoHandler{
	private Log logger;
	private MasterManager masterManager;
	
	public MasterClientHandler(MasterManager masterManager){
		this.logger = LogFactory.getLog(MasterClientHandler.class);
		this.masterManager = masterManager;
	}
	
    public void messageReceived(IoSession session, Object message) {
    	if (!(message instanceof TaskPushMessage)){
    		logger.error("master recived a error message from client!"+ session);
    	}
    	logger.info("masterManager process task push");
    	Task task = ((TaskPushMessage)message).getTask();
    	masterManager.processTaskPush(task);
    }
    
	public void sessionOpened(IoSession session) {
		logger.error("session is opened, master connected to the client!"+ session);
		masterManager.processClientRegister(session);
		masterManager.operate("client", "add", session);
	}//end for
	
	public void sessionClosed(IoSession session) throws Exception {
    	logger.error("sessionClosed, master can not connect to the client!"+ session);
		masterManager.operate("client", "remove", session);
    	session.close(true);
//		MasterManager.sessionToClient = null;
	}
	
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
    	logger.error(cause.getMessage());
    	cause.printStackTrace();
    	logger.error("exceptionCaught, master can not connect to the client!"+ session);
    	session.close(true);
//    	MasterManager.sessionToClient = null;
    }

	@Override
	public void messageSent(IoSession arg0, Object arg1) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionCreated(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
		// TODO Auto-generated method stub
		
	}
}
